import {
    productionPrdReportCreate,
    productionPrdReportFixDate,
    productionPrdReportGet,
    productionPrdReportGetDate,
    productionPrdReportHistoryGet,
    productionPrdReportHistoryPage,
    productionPrdReportHistorySetMaster,
    productionPrdReportUpdate,
    productionPrdReportUpdateStatus
} from '../../../../../api/production/xsReport';
import { formatDate, tipsBar } from '../../../../../utils/jk/jk-tool';
import { spinProcessPage } from '@/api/technology/process';

import {
    openStateList,
    reportStateList
} from '../../../../../utils/jk/status-option-list';
import { workforcemanagementScheduleList } from '../../../../../api/schedule/scheduling';
import {
    mathJsAdd,
    mathJsDiv,
    mathJsMul,
    mathJsSub
} from '../../../../../utils/jk/jk-cals';
import handlerCache from '../../../../../mixins/handler-cache';
import supplementaryPlanMx from '../../../order/components/form-box/supplementaryPlanMx';
import expandRow from './expand-row';
import XEUtils, { isNumber } from 'xe-utils';
let _this = null;
export default {
    mixins: [handlerCache, supplementaryPlanMx],
    components: {
        expandRow
    },
    props: {
        pageType: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            prefix: 'production:prdReport',
            apiItem: {
                save: productionPrdReportCreate,
                update: productionPrdReportUpdate
            },
            fixStateList: [
                { id: -1, name: '计算失败', color: '#F95457' },
                { id: 0, name: '未计算', color: '#ff9900' },
                { id: 1, name: '计算中', color: '#2b85e4' },
                { id: 2, name: '计算完成', color: '#0bab5b' }
            ],
            productList: [],
            tableLoading: false,
            reportStateList: reportStateList,
            selectOrderDialogState: false,
            selectMaterialDialogState: false,
            openStateList: openStateList,
            dataId: null,
            showLoading: false,
            processCode: undefined,
            saveBtnLoading: false,
            releaseBtnLoading: false,
            workshopList: [],
            processList: [],
            saveDialogState: false,
            scheduleShiftList: [],
            historyData: [],
            ruleForm: {
                code: '',
                type: 2,
                generateType: 1,
                belongDate: '',
                shiftWeightQty: 0,
                historyCount: 0,
                prdReportMachineList: [],
                processCode: '',
                processId: null,
                processName: '',
                scheduleShiftId: null,
                shiftElectricEnergy: null,
                shiftId: null,
                shiftName: '',
                shiftOutput: null,
                shiftQty: null,
                wasteRate: null,
                workshopId: null,
                workshopName: '',
                remark: ''
            },
            rules: {
                processId: [{ required: true, trigger: 'change' }],
                belongDate: [{ required: true, trigger: 'change' }],
                scheduleShiftId: [{ required: true, trigger: 'change' }],
                workshopId: [{ required: true, trigger: 'change' }]
            },
            unReleaseBtnLoading: false
        };
    },
    methods: {
        onDelMachine(item, index) {
            const data = this.ruleForm.prdReportMachineList.filter(
                (i) => i.machineCode === item.machineCode
            );
            if (data.length === 1) {
                const row = this.ruleForm.prdReportMachineList[index];
                // if (row) {
                //     const fieldsToClear = [
                //       'productName',
                //       'batchCode',
                //       'openSpinCount',
                //       'collectShiftQty',
                //       'totalProductQty',
                //       'xsSingleSpinGram',
                //       'shiftQty',
                //       'peopleTotalQty'
                //     ];
                //     fieldsToClear.forEach(key => {
                //       row[key] = undefined;
                //     });
                //   }
                if (row) {
                    Object.keys(row).forEach((key) => {
                        if (key !== 'machineName' && key !== 'machineCode') {
                            row[key] = undefined;
                        }
                    });
                }
            } else {
                this.ruleForm.prdReportMachineList.splice(index, 1);
            }
        },
        onMachinePlus(item, index) {
            this.ruleForm.prdReportMachineList.splice(index + 1, 0, {
                machineCode: item.machineCode,
                machineId: item.machineId,
                machineName: item.machineName
            });
        },
        // 绑定订单
        handleBindOrder(scope) {
            this.bindData = scope;
            this.processCode = scope.row.machineName.slice(0, 2);
            if (
                scope.row.machineCode.slice(0, 2) === 'LT' ||
                scope.row.machineCode.slice(0, 2) === 'XS'
            ) {
                this.selectOrderDialogState = true;
            } else {
                this.selectMaterialDialogState = true;
            }
            this.pageTypeOrder = 'add';
        },
        onVisibleChangeOfSelectOrderDialog(e) {
            this.selectOrderDialogState = e;
        },
        onVisibleChangeOfSelectMaterialDialog(e) {
            this.selectMaterialDialogState = e;
        },
        onConfirmBtnOfSelectOrderDialog(selectData) {
            // console.log(selectData.row, '选中的一条');// 外面表格的数据 this.bindData
            // 这是选中radio的数据selectData
            const batchCode =
                selectData.row.productOrderBatchList.length > 0
                    ? selectData.row.productOrderBatchList[0].batchCode
                    : '';
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productName',
                `${selectData.row.productName + ' - ' + '手动修正'}`
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productOrderId',
                selectData.row.id
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'batchCode',
                batchCode
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productCode',
                selectData.row.productCode
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productId',
                selectData.row.productId
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'gramWeight',
                selectData.row.gramWeight
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'meters',
                selectData.row.meters
            );
            // console.log(this.ruleForm.prdReportMachineList[this.bindData.rowIndex]);
            this.selectOrderDialogState = false;
        },
        onConfirmBtnOfSelectMaterialDialog(selectData) {
            // console.log(selectData.row, 'selectData');

            const batchCode = selectData.row ? selectData.row : '';
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productName',
                `${batchCode.name + ' - ' + '手动修正'}`
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productCode',
                batchCode.code
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'productId',
                batchCode.id
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'gramWeight',
                selectData.row.gramWeight
            );
            this.$set(
                this.ruleForm.prdReportMachineList[this.bindData.rowIndex],
                'meters',
                selectData.row.meters
            );
            this.selectMaterialDialogState = false;
        },
        footerMethod({ columns, data }) {
            const keys = [
                'peopleTotalQty',
                'machineReadingQty',
                'shiftQty',
                'totalProductQty'
            ];
            return [
                columns.map((column, columnIndex) => {
                    if (columnIndex === 0) {
                        return '合计';
                    }
                    if (keys.includes(column.field)) {
                        return XEUtils.sum(data, column.field) + 'kg';
                    }
                    return null;
                })
            ];
        },
        mergeColMethod({ row, _rowIndex, column, visibleData }) {
            const prevRow = visibleData[_rowIndex - 1];
            let nextRow = visibleData[_rowIndex + 1];
            if (column.property === 'machineName') {
                if (
                    prevRow &&
                    prevRow.machineName &&
                    prevRow.machineName === row.machineName
                ) {
                    return { rowspan: 0, colspan: 0 };
                } else {
                    let countRowspan = 1;
                    while (
                        nextRow &&
                        nextRow.machineName &&
                        nextRow.machineName === row.machineName
                    ) {
                        nextRow = visibleData[++countRowspan + _rowIndex];
                    }
                    if (countRowspan > 1) {
                        return { rowspan: countRowspan, colspan: 1 };
                    }
                }
            } else if (column.property === 'totalProductQty') {
                if (
                    prevRow &&
                    prevRow.machineName === row.machineName &&
                    prevRow.totalProductQty === row.totalProductQty
                ) {
                    return { rowspan: 0, colspan: 0 };
                } else {
                    let countRowspan = 1;
                    while (
                        nextRow &&
                        nextRow.machineName === row.machineName &&
                        nextRow.totalProductQty === row.totalProductQty
                    ) {
                        nextRow = visibleData[++countRowspan + _rowIndex];
                    }
                    if (countRowspan > 1) {
                        return { rowspan: countRowspan, colspan: 1 };
                    }
                }
            } else if (column.property === 'peopleTotalQty') {
                if (
                    prevRow &&
                    prevRow.machineName === row.machineName &&
                    prevRow.peopleTotalQty === row.peopleTotalQty
                ) {
                    return { rowspan: 0, colspan: 0 };
                } else {
                    let countRowspan = 1;
                    while (
                        nextRow &&
                        nextRow.machineName === row.machineName &&
                        nextRow.peopleTotalQty === row.peopleTotalQty
                    ) {
                        nextRow = visibleData[++countRowspan + _rowIndex];
                    }
                    if (countRowspan > 1) {
                        return { rowspan: countRowspan, colspan: 1 };
                    }
                }
            } else if (column.property === 'machineReadingQty') {
                if (
                    prevRow &&
                    prevRow.machineName === row.machineName &&
                    prevRow.machineReadingQty === row.machineReadingQty
                ) {
                    return { rowspan: 0, colspan: 0 };
                } else {
                    let countRowspan = 1;
                    while (
                        nextRow &&
                        nextRow.machineName === row.machineName &&
                        nextRow.machineReadingQty === row.machineReadingQty
                    ) {
                        nextRow = visibleData[++countRowspan + _rowIndex];
                    }
                    if (countRowspan > 1) {
                        return { rowspan: countRowspan, colspan: 1 };
                    }
                }
            }
        },
        onUnReleaseBtn() {
            this.unReleaseBtnLoading = true;
            productionPrdReportUpdateStatus({
                id: this.ruleForm.id
            }).then((res) => {
                this.unReleaseBtnLoading = false;
                if (res.data.status === 200) {
                    this.$tipsBar(this, 'save');
                    this.$store.dispatch('tagsView/delView', {
                        path: this.$route.path
                    });
                    this.$toOtherRouter({
                        name: `editProductionReport`,
                        query: {
                            id: this.ruleForm.id,
                            processCode: this.$route.query.processCode
                        }
                    });
                }
            });
        },
        clearCacheMethod() {
            Object.assign(this.$data, this.$options.data());
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
                this.getDependentData();
            });
        },
        onUseHistory(row) {
            this.$confirm(`确定将该版本(${row.version}.0)设置为主版本吗?`, {
                type: 'warning'
            }).then(() => {
                return productionPrdReportHistorySetMaster(
                    {},
                    { id: row.id }
                ).then((res) => {
                    if (res.data.status === 200) {
                        this.$toOtherRouter({
                            name: 'detailXsReport',
                            query: {
                                id: res.data.res
                            }
                        });
                        this.getDependentData();
                    }
                });
            });
        },
        // 输入,开始能耗表数
        onStartElectricEnergy(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'startElectricEnergy',
                e
            );
            // 针对并线合并-如：并线4-1右、并线4-1左, 能耗只算其中一个机台，其余赋值为0
            if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
                this.ruleForm.prdReportMachineList.forEach((x) => {
                    if (x.machineId !== scope.row.machineId) {
                        if (
                            x.machineName &&
                            x.machineName.substring(
                                0,
                                x.machineName.length - 1
                            ) ===
                                scope.row.machineName.substring(
                                    0,
                                    scope.row.machineName.length - 1
                                )
                        ) {
                            this.$set(x, 'startElectricEnergy', 0);
                            this.$set(x, 'shiftElectricEnergy', 0);
                        }
                    }
                });
            }
            this.calMachineItemVal(scope);
        },
        // 输入,结束能耗表数
        onEndElectricEnergy(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'endElectricEnergy',
                e
            );
            // 针对并线合并-如：并线4-1右、并线4-1左, 能耗只算其中一个机台，其余赋值为0
            if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
                this.ruleForm.prdReportMachineList.forEach((x) => {
                    if (x.machineId !== scope.row.machineId) {
                        if (
                            x.machineName &&
                            x.machineName.substring(
                                0,
                                x.machineName.length - 1
                            ) ===
                                scope.row.machineName.substring(
                                    0,
                                    scope.row.machineName.length - 1
                                )
                        ) {
                            this.$set(x, 'endElectricEnergy', 0);
                            this.$set(x, 'shiftElectricEnergy', 0);
                        }
                    }
                });
            }
            this.calMachineItemVal(scope);
        },
        calTotal() {
            let valM = 0;
            let valKg = 0;
            let valKgWeight = 0;
            let valEn = 0;
            this.ruleForm && this.ruleForm.prdReportMachineList
                ? this.ruleForm.prdReportMachineList.forEach((x) => {
                      valM = mathJsAdd(x.shiftOutput || 0, valM);
                      valKg = mathJsAdd(x.shiftQty || 0, valKg);
                      valKgWeight = mathJsAdd(
                          x.shiftWeightQty || 0,
                          valKgWeight
                      );
                      valEn = mathJsAdd(x.shiftElectricEnergy || 0, valEn);
                  })
                : [];
            this.$set(this.ruleForm, 'shiftOutput', valM);
            this.$set(this.ruleForm, 'shiftQty', valKg);
            this.$set(this.ruleForm, 'shiftWeightQty', valKgWeight);
            this.$set(this.ruleForm, 'shiftElectricEnergy', valEn);
        },
        // 输入,开始产量表数
        onStartOutput(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'startOutput',
                e
            );
            this.calMachineItemVal(scope);
        },
        // 输入,当班能耗表数
        onShiftElectricEnergy(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'shiftElectricEnergy',
                e
            );
            this.calMachineItemVal(scope);
        },
        // 输入,结束产量表数
        onEndOutput(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'endOutput',
                e
            );
            this.calMachineItemVal(scope);
        },
        onOutputRatio(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'outputRatio',
                e
            );
            this.calMachineItemVal(scope);
        },
        onOpenSpinCount(e, scope) {
            this.$set(
                this.ruleForm.prdReportMachineList[scope.rowIndex],
                'openSpinCount',
                e
            );
            this.calMachineItemVal(scope);
        },
        // 计算设备总产量
        calMachineTotalVal() {
            const machineGroupInfo = {};
            this.ruleForm.prdReportMachineList.forEach((x) => {
                if (machineGroupInfo[x.machineName]) {
                    machineGroupInfo[x.machineName].totalProductQty = mathJsAdd(
                        machineGroupInfo[x.machineName].totalProductQty,
                        x.collectShiftQty || 0
                    );
                    machineGroupInfo[x.machineName].peopleTotalQty = mathJsAdd(
                        machineGroupInfo[x.machineName].peopleTotalQty,
                        x.shiftQty || 0
                    );
                } else {
                    machineGroupInfo[x.machineName] = {
                        totalProductQty: x.collectShiftQty || 0,
                        peopleTotalQty: x.shiftQty || 0
                    };
                }
            });
            this.ruleForm.prdReportMachineList.forEach((x) => {
                if (machineGroupInfo[x.machineName]) {
                    this.$set(
                        x,
                        'totalProductQty',
                        machineGroupInfo[x.machineName].totalProductQty
                    );
                    this.$set(
                        x,
                        'peopleTotalQty',
                        machineGroupInfo[x.machineName].peopleTotalQty
                    );
                }
            });
        },
        // 开台锭数修改时
        onOpenSpinCountChange(e, scope) {
            if (
                this.ruleForm.processCode &&
                ['CS', 'XS', 'LT'].includes(this.ruleForm.processCode)
            ) {
                /**
                 * 计算当班产量表量KG
                 * */
                // 是单锭时
                if (scope.row.ifSpinOutput) {
                    // 单位是公斤时, 当班人工产量(kg) = 采集表数 * 开台锭数
                    if (scope.row.useMachineOutputKg) {
                        let totalKg = mathJsMul(
                            scope.row.rawOutput || 0,
                            scope.row.openSpinCount
                        );
                        totalKg = parseFloat(totalKg.toFixed(2));
                        this.$set(
                            this.ruleForm.prdReportMachineList[scope.rowIndex],
                            'shiftQty',
                            totalKg
                        );
                    } else {
                        // 单位是米时, 当班人工产量(kg) = 采集表数 / 米长 * 克重 / 1000 * 开台锭数
                        let totalKg = scope.row.meters
                            ? mathJsDiv(
                                  scope.row.rawOutput || 0,
                                  scope.row.meters
                              )
                            : 0;
                        totalKg = mathJsMul(totalKg, scope.row.gramWeight || 0);
                        totalKg = mathJsMul(
                            totalKg,
                            scope.row.openSpinCount || 0
                        );
                        totalKg = mathJsDiv(totalKg, 1000);
                        totalKg = parseInt(mathJsMul(totalKg, 100));
                        totalKg = mathJsDiv(totalKg, 100);
                        this.$set(
                            this.ruleForm.prdReportMachineList[scope.rowIndex],
                            'shiftQty',
                            totalKg
                        );
                        this.$set(
                            this.ruleForm.prdReportMachineList[scope.rowIndex],
                            'collectShiftQty',
                            totalKg
                        );
                    }
                }
            }
            this.calMachineTotalVal();
        },
        // 根据"当班人工产量(M)"计算"当班人工产量(kg)"
        onShiftOutputChange(e, scope) {
            if (
                this.ruleForm.processCode &&
                ['CS', 'XS', 'LT'].includes(this.ruleForm.processCode)
            ) {
                // 当班产量表量KG = 当班产量表量 / 米长 * 克重 / 1000
                let totalKg = 0;
                totalKg = scope.row.meters
                    ? mathJsDiv(e || 0, scope.row.meters)
                    : 0;
                totalKg = mathJsMul(totalKg, scope.row.gramWeight || 0);
                totalKg = mathJsDiv(totalKg, 1000);
                // 是单锭时需 * 开台锭数
                if (scope.row.ifSpinOutput) {
                    totalKg = mathJsMul(totalKg, scope.row.openSpinCount || 0);
                }
                totalKg = parseInt(mathJsMul(totalKg, 100));
                totalKg = mathJsDiv(totalKg, 100);
                this.$set(
                    this.ruleForm.prdReportMachineList[scope.rowIndex],
                    'shiftQty',
                    totalKg
                );
            }
            this.calMachineTotalVal();
        },
        /**
         * 细纱23~26的当班人工产量kg的计算逻辑
         * 单锭克数 = 采集表数 / 1000 * 克重
         * 当班人工产量kg = 单锭克重 * 开台锭数 / 1000
         *
         * */
        onXsSingleSpinGramChange(e, scope) {
            if (
                scope.row.machineCode &&
                ['XS023', 'XS024', 'XS025', 'XS026'].includes(
                    scope.row.machineCode
                )
            ) {
                let totalKg = 0;
                // 是单锭时
                if (scope.row.ifSpinOutput) {
                    totalKg = mathJsMul(e, scope.row.openSpinCount);
                    totalKg = mathJsDiv(totalKg, 1000);
                    totalKg = parseInt(totalKg * 100);
                    totalKg = totalKg / 100;
                }
                this.$set(
                    this.ruleForm.prdReportMachineList[scope.rowIndex],
                    'shiftQty',
                    totalKg
                );

                this.calMachineTotalVal();
            }
        },
        // 根据"当班人工产量(kg)"计算"当班人工产量(m)"
        onShiftQtyChange(e, scope) {
            if (
                this.ruleForm.processCode &&
                ['CS', 'XS', 'LT'].includes(this.ruleForm.processCode)
            ) {
                // 当班产量m = 当班产量kg * 1000 / 克重 * 米长
                const times = scope.row.gramWeight
                    ? mathJsDiv((e || 0) * 1000, scope.row.gramWeight)
                    : 0;
                let totalM = mathJsMul(times, scope.row.meters || 0);
                // 是单锭时需 * 开台锭数
                if (scope.row.ifSpinOutput) {
                    totalM = mathJsMul(totalM, scope.row.openSpinCount || 0);
                }
                totalM = parseInt(mathJsMul(totalM, 100));
                totalM = mathJsDiv(totalM, 100);
                this.$set(
                    this.ruleForm.prdReportMachineList[scope.rowIndex],
                    'csRawOutput',
                    totalM
                );
            }
            this.calMachineTotalVal();
        },
        calMachineItemVal(scope) {
            /* /!** 第一,计算当班产量(M) *!/
			// 当班产量表量(M) = 当班产量表量 = (结束产量表数 - 开始产量表数) * 系数
			if (scope.row.startOutput < scope.row.endOutput) {
				let val = mathJsSub((scope.row.endOutput || 0), (scope.row.startOutput || 0));
				val = mathJsMul(val, scope.row.outputRatio);
				val = parseFloat(val.toFixed(2));
				// 是单锭时需 * 开台锭数
				if (scope.row.ifSpinOutput) {
					val = mathJsMul(val, scope.row.openSpinCount || 0);
				}
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'differenceValue', val);
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftOutput', val);
			} else {
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'differenceValue', 0);
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftOutput', 0);
			}
			// 当班产量表量KG = 当班产量表量 / 米长 * 克重 / 1000
			let valKg1 = 0;
			if (scope.row.meters) {
				valKg1 = mathJsDiv(scope.row.differenceValue, scope.row.meters);
				valKg1 = mathJsMul(valKg1, scope.row.gramWeight || 0);
				valKg1 = mathJsDiv(valKg1, 1000);
				valKg1 = parseFloat(valKg1.toFixed(2));

				// meters表示每米的公斤数 = 克重 / 米长 * 1000
				// valKg1 = mathJsMul(scope.row.differenceValue, scope.row.meters || 0);
				// valKg1 = parseFloat(valKg1.toFixed(2));
			}
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftQty', valKg1);

			/!** 第二,计算当班能耗表数 *!/
			// 当班能耗表数 = 结束能耗表数 - 开始能耗表数
			let energyVal = mathJsSub(scope.row.endElectricEnergy, scope.row.startElectricEnergy);
			energyVal = parseFloat(energyVal.toFixed(2));
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftElectricEnergy', energyVal);*/
        },
        onWorkshopChange() {
            this.$set(this.ruleForm, 'prdReportMachineList', []);
            this.$set(this.ruleForm, 'scheduleShiftId', null);
            this.$set(this.ruleForm, 'shiftId', null);
            this.$set(this.ruleForm, 'shiftName', null);
            this.scheduleShiftList = [];
            this.getProcessListRequest(); // 区域变化后工序变化
            this.getDateScheduleShiftOptionRequest(); // 区域变化后报工班次变化
        },
        getProcessListRequest() {
            if (!this.ruleForm.workshopId) {
                return;
            }
            return spinProcessPage({
                auditState: 1,
                workshopId: this.ruleForm.workshopId
            }).then((res) => {
                if (res.data.status === 200) {
                    this.processList = res.data.res;
                    this.ruleForm.processId = this.processList[0]?.id;
                }
            });
        },
        onProcessChange(e) {
            const item = this.processList.find((x) => x.id === e) || {};
            this.$set(this.ruleForm, 'processCode', item.code);
            this.$set(this.ruleForm, 'processName', item.name);
            this.$set(this.ruleForm, 'prdReportMachineList', []);
            this.getOpenMachineListRequest();
        },
        onJumpList() {
            this.$store.dispatch('tagsView/delView', {
                path: this.$route.path
            });
            this.$toMainRouter({
                name: `ProductionReport`
            });
        },
        onJump(id) {
            this.$store.dispatch('tagsView/delView', {
                path: this.$route.path
            });
            this.$toMainRouter({
                name: `editProductionReport`,
                query: {
                    id: id
                }
            });
        },
        setDependentDataOfForm() {
            const params = JSON.parse(JSON.stringify(this.ruleForm));
            params.prdReportMachineList.forEach((x) => {
                delete x.loading;
            });

            const workshopItem =
                this.workshopList.find((x) => x.id === params.workshopId) || {};
            params.workshopCode = workshopItem.code;
            params.workshopName = workshopItem.name;

            const processItem =
                this.processList.find((x) => x.id === params.processId) || {};
            params.processCode = processItem.code;
            params.processName = processItem.name;

            if (!this.dataId) {
                const shiftItem =
                    this.scheduleShiftList.find(
                        (x) => x.id === params.scheduleShiftId
                    ) || {};
                params.shiftId = shiftItem.shiftId;
                params.shiftName = shiftItem.shiftName;
            }
            return params;
        },
        onConfirmBtn(from = 'save') {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    // 核实
                    if (from === 'release') {
                        this.releaseRequest();
                    } else {
                        this.createAndUpdateRequest();
                    }
                } else {
                    this.$tipsBar(this, 'validator');
                }
            });
        },
        createAndUpdateRequest() {
            this.saveBtnLoading = true;
            // 新增
            if (!this.dataId) {
                this.ruleForm.id = null;
                productionPrdReportCreate(this.setDependentDataOfForm()).then(
                    (res) => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            this.onJump(res.data.res);
                        }
                    }
                );
                return;
            }
            // 编辑
            productionPrdReportUpdate(this.setDependentDataOfForm()).then(
                (res) => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.getDependentData();
                    }
                }
            );
        },
        releaseRequest() {
            this.releaseBtnLoading = true;
            // 先保存再核实
            productionPrdReportUpdate(this.setDependentDataOfForm()).then(
                (res) => {
                    if (res.data.status === 200) {
                        productionPrdReportUpdateStatus({
                            id: this.ruleForm.id
                        }).then((res) => {
                            this.releaseBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$store.dispatch('tagsView/delView', {
                                    path: this.$route.path
                                });
                                this.$toOtherRouter({
                                    name: `detailProductionReport`,
                                    query: {
                                        id: this.ruleForm.id,
                                        processCode:
                                            this.$route.query.processCode || ''
                                    }
                                });
                            }
                        });
                    } else {
                        this.getDependentData();
                        this.releaseBtnLoading = false;
                    }
                }
            );
        },
        onVisibleChange(e) {
            this.$emit('on-visible-change', e);
            if (!e) {
                Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.$refs.ruleForm.resetFields();
                });
            }
        },
        getProductList() {
            const productConf = {};
            if (this.ruleForm.prdReportMachineList) {
                this.ruleForm.prdReportMachineList.forEach((x) => {
                    if (productConf[x.batchCode]) {
                        productConf[x.batchCode].shiftQty = mathJsAdd(
                            x.shiftQty,
                            productConf[x.batchCode].shiftQty || 0
                        );
                        productConf[x.batchCode].differenceValue = mathJsAdd(
                            x.differenceValue,
                            productConf[x.batchCode].differenceValue || 0
                        );
                    } else {
                        productConf[x.batchCode] = {
                            batchCode: x.batchCode,
                            productName: x.productName,
                            differenceValue: x.differenceValue,
                            shiftQty: x.shiftQty
                        };
                    }
                });
            }
            this.productList = [];
            for (const key in productConf) {
                this.productList.push(productConf[key]);
            }
        },
        getDetailRequest() {
            let api = null;
            if (
                this.$route.query.formPage &&
                this.$route.query.formPage === 'history'
            ) {
                api = productionPrdReportHistoryGet;
            } else {
                api = productionPrdReportGet;
            }
            return api({ id: this.$route.query.id }).then((res) => {
                this.showLoading = false;
                if (res.data.status === 200) {
                    const resData = res.data.res
                        ? JSON.parse(JSON.stringify(res.data.res))
                        : {};
                    resData.prdReportMachineList = resData.prdReportMachineList
                        ? resData.prdReportMachineList.map((x) => {
                              x.loading = false;
                              return x;
                          })
                        : [];
                    const arr = this.clearBxEnergy(
                        resData.prdReportMachineList || []
                    );
                    resData.prdReportMachineList = arr;
                    this.ruleForm = resData;
                    this.getErrorInfoRequest({
                        workshopId: this.ruleForm.workshopId,
                        processCode: this.ruleForm.processCode,
                        shiftId: this.ruleForm.shiftId,
                        belongDate: this.ruleForm.belongDate
                            ? [
                                  this.ruleForm.belongDate,
                                  this.ruleForm.belongDate
                              ]
                            : [],
                        state: 0
                    });
                    this.getProductList();
                    this.calTotal();
                }
            });
        },
        onSeeHistory(row) {
            this.$toOtherRouter({
                name: 'detailXsReport',
                query: {
                    id: row.id,
                    formPage: 'history'
                }
            });
            this.getDependentData();
        },
        onScheduleShiftChange(e) {
            let item = {};
            if (e) {
                item = this.scheduleShiftList.find((x) => x.id === e);
            } else {
                item = {
                    id: null,
                    shiftId: null,
                    shiftName: null,
                    scheduleId: null
                };
            }
            this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
            this.$set(this.ruleForm, 'scheduleShiftId', item.id);
            this.$set(this.ruleForm, 'shiftId', item.shiftId);
            this.$set(this.ruleForm, 'shiftName', item.shiftName);
            this.getOpenMachineListRequest();
        },
        getOpenMachineListRequest() {
            if (
                this.ruleForm.workshopId &&
                this.ruleForm.processId &&
                this.ruleForm.belongDate &&
                this.ruleForm.scheduleShiftId
            ) {
                this.tableLoading = true;
                productionPrdReportGetDate({
                    workshopId: this.ruleForm.workshopId,
                    processId: this.ruleForm.processId,
                    shiftId: this.ruleForm.shiftId,
                    scheduleShiftId: this.ruleForm.scheduleShiftId,
                    belongDate: this.ruleForm.belongDate
                }).then((res) => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const arr = this.clearBxEnergy(res.data.res || []);
                        this.$set(this.ruleForm, 'prdReportMachineList', arr);
                        this.calTotal();
                    }
                });
            }
        },
        // 清除并线的能耗（左、右，能耗只计算其中一个）
        clearBxEnergy(arr) {
            const conf = {};
            arr.forEach((x) => {
                if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
                    if (
                        x.machineName &&
                        !conf[
                            x.machineName.substring(0, x.machineName.length - 1)
                        ]
                    ) {
                        conf[
                            x.machineName.substring(0, x.machineName.length - 1)
                        ] = x.machineName.substring(
                            0,
                            x.machineName.length - 1
                        );
                    } else {
                        x.startElectricEnergy = 0;
                        x.endElectricEnergy = 0;
                        x.shiftElectricEnergy = 0;
                    }
                }
            });
            return arr;
        },
        getDateScheduleShiftOptionRequest() {
            if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
                return workforcemanagementScheduleList({
                    belongDate: [
                        this.ruleForm.belongDate,
                        this.ruleForm.belongDate
                    ],
                    workshopId: this.ruleForm.workshopId
                }).then((res) => {
                    if (res.data.status === 200) {
                        const resData = res.data.res;
                        if (resData && resData.length) {
                            this.scheduleShiftList =
                                resData[0].scheduleShiftList;
                        } else {
                            tipsBar(
                                this,
                                'custom',
                                'warning',
                                '当前时间未排班，请排班后再操作！'
                            );
                        }
                    }
                });
            }
        },
        onDateChange() {
            this.$set(this.ruleForm, 'scheduleShiftId', null);
            this.$set(this.ruleForm, 'shiftName', null);
            this.$set(this.ruleForm, 'shiftId', null);
            this.$set(this.ruleForm, 'prdReportMachineList', []);
            this.scheduleShiftList = [];
            this.getDateScheduleShiftOptionRequest();
        },
        getHistoryDataRequest() {
            return productionPrdReportHistoryPage({
                selectMaster: false,
                prdReportId: this.ruleForm.prdReportId
                    ? this.ruleForm.prdReportId
                    : this.ruleForm.id
            }).then((res) => {
                if (res.data.status === 200) {
                    this.historyData = res.data.res;
                }
            });
        },
        async getDependentData() {
            this.showLoading = true;
            this.dataId = this.$route.query.id
                ? Number(this.$route.query.id)
                : null;
            this.processList = this.$store.state.user.userProcess.processList;
            if (this.pageType !== 'detail') {
                this.workshopList =
                    this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(
                        this.ruleForm,
                        'processId',
                        this.$route.query.processId
                            ? Number(this.$route.query.processId)
                            : this.$store.state.user.userProcess
                                  .defaultProcessId
                    );
                    this.$set(
                        this.ruleForm,
                        'workshopId',
                        this.$route.query.workshopId
                            ? Number(this.$route.query.workshopId)
                            : this.$store.state.user.userWorkshop
                                  .defaultWorkshopId
                    );
                    this.$set(
                        this.ruleForm,
                        'belongDate',
                        formatDate(Date.now())
                    );
                    this.getProcessListRequest();
                }
            }
            if (this.dataId) await this.getDetailRequest();
            await this.getDateScheduleShiftOptionRequest();
            await this.getHistoryDataRequest();
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            });
            this.showLoading = false;
        }
    },
    watch: {
        ruleForm: {
            handler() {
                this.calTotal();
                this.getProductList();
                this.$nextTick(() => {
                    this.$refs.jkTable.$refs.xTable.updateFooter();
                    this.$refs.machineTable.$refs.xTable.updateFooter();

                    this.$refs.jkTable.$refs.xTable.refreshColumn();
                    this.$refs.machineTable.$refs.xTable.refreshColumn();
                });
            },
            deep: true,
            immediate: true
        }
    },
    mounted() {
        _this = this;
    }
};
